package cn.hy.dataSync.statistics.container.collector;


import cn.hy.dataSync.config.TaskConfig;
import cn.hy.dataSync.job.State;
import cn.hy.dataSync.statistics.communication.Communication;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 针对一次 jobId，相当于一次 job （同步）任务统计（收集）
 */
public abstract class AbstractCollector {

    private String jobId;

    /**
     * key -> taskId
     * value -> Communication,一次任务的统计数据
     */
    private Map<Integer, Communication> taskCommunicationMap = new ConcurrentHashMap<>();

    public String getJobId() {
        return jobId;
    }

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    /**
     * 任务对象配置 -> 注册统计信息
     * @param taskConfigs taskConfigs
     */
    public void registerTaskCommunication(final List<TaskConfig> taskConfigs) {
        for (TaskConfig taskConfig : taskConfigs) {
            int taskId = taskConfig.getTaskId();
            this.taskCommunicationMap.put(taskId, new Communication());
        }
    }

    /**
     * 将所有任务中的信息（Communication）统计成为一个，表示该次job 已经结束
     * @return
     */
    public Communication collectFromTask() {
        Communication communication = new Communication();
        communication.setState(State.SUCCEEDED);

        for (Communication taskCommunication :
                this.taskCommunicationMap.values()) {
            communication.mergeFrom(taskCommunication);
        }

        return communication;
    }

    public Map<Integer, Communication> getTaskCommunicationMap() {
        return taskCommunicationMap;
    }

    public Communication getTaskCommunication(Integer taskId) {
        return taskCommunicationMap.get(taskId);
    }
}
